package com.chen.utils;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chen.common.VxConfig;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VxUtils {

    /**
     * 根据code获取微信openid
     * @param code
     * @return
     */
    public static String getWeiXinOpenid(String code) {
        String urlStr = VxConfig.VXHttpUrl.getOpenidUrl+"?appid=" + VxConfig.AppID
                + "&secret=" + VxConfig.AppSecret
                + "&grant_type=authorization_code&js_code=" + code;
        log.info("[appid]:{} [secret]:{} [js_code]:{}",VxConfig.AppID,VxConfig.AppSecret,code );
        String body = HttpUtil.get(urlStr);
        JSONObject result = JSONUtil.parseObj(body);
        Integer errcode = result.getInt("errcode");
        if (errcode == null || errcode.equals(0)){
            log.info("[获取openid成功] 回复报文:{}", result.getStr("openid"));
            return result.getStr("openid");
        }else {
            log.error("[获取openid失败] 回复报文:{}", body);
            return null;
        }
    }

    /**
     * 获取接口凭据
     * @param
     * @return
     */
    public static String getAccessToken () {
        String urlStr = VxConfig.VXHttpUrl.getAccessTokenUrl;
        String jsonParams = "{\"appid\": \""+VxConfig.AppID+"\", \"secret\": \""+VxConfig.AppSecret+"\", \"grant_type\": \"client_credential\"}";
        System.out.println(jsonParams);
        String body = HttpUtil.post(urlStr,jsonParams);
        JSONObject result = JSONUtil.parseObj(body);
        Integer errcode = result.getInt("errcode");
        if (errcode == null || errcode.equals(0)){
            log.info("[获取接口凭据成功] 回复报文:{}", body);
            return result.getStr("access_token");
       } else {
            log.error("[获取接口凭据错误] 回复报文:{}", body);
            return null;
        }
    }


    /**
     * 获取手机号
     * @param code
     * @return
     */
    public static String getPhone (String code) {
        String urlStr = VxConfig.VXHttpUrl.getPhoneUrl +"?access_token="+getAccessToken();
        System.out.println(urlStr);
        String jsonParams = "{\"code\": \""+code+"\"}";
        String body = HttpUtil.post(urlStr,jsonParams);
        JSONObject result = JSONUtil.parseObj(body);
        Integer errcode = result.getInt("errcode");
        if (errcode == null || errcode.equals(0)) {
            log.info("[获取手机接口成功] 回复报文:{}", body);
            return result.getStr("phone_info");
        }else {
            log.error("[获取手机接口错误] 回复报文:{}", body);
            return null;
        }
    }



}
